package yuan.node;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.*;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.data.Stat;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

/**
 * @version: 1.0
 * @Description: TODO
 * @author: zZmH
 * @date: 2020/09/12 20:55
 */


public class CuratorWatcher {
    public static final String ip = "192.168.190.128:2181";
    CuratorFramework client;

    @Before
    public void before() {
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
        client = CuratorFrameworkFactory
                .builder()
                .connectString(ip)
                .sessionTimeoutMs(5000)
                .retryPolicy(retryPolicy)
                .namespace("create")
                .build();
        client.start();

    }

    @After
    public void after() {
        client.close();
    }

    @Test
    public void test1() throws Exception {
        NodeCache nodeCache = new NodeCache(client, "/watcher1");
        nodeCache.start();

        nodeCache.getListenable()
                .addListener(new NodeCacheListener() {
                    @Override
                    public void nodeChanged() throws Exception {
                        System.out.println(nodeCache.getCurrentData().getPath());
                        System.out.println(nodeCache.getCurrentData().getData());

                    }
                });
        Thread.sleep(50000);
        System.out.println("end");

        nodeCache.close();
    }
    @Test
    public void test3() throws Exception {
        PathChildrenCache childrenCache = new PathChildrenCache(client, "/watcher1", true);
        childrenCache.start();
        childrenCache.getListenable()
                .addListener(new PathChildrenCacheListener() {
                    @Override
                    public void childEvent(CuratorFramework curatorFramework, PathChildrenCacheEvent pathChildrenCacheEvent) throws Exception {
                        System.out.println(pathChildrenCacheEvent.getType());
                        System.out.println(pathChildrenCacheEvent.getData().getData());

                    }
                });

        Thread.sleep(100000);

        childrenCache.close();
    }
    @Test
    public void test2() throws Exception {

    }
}
